<?php
namespace App\Http\Controllers\ApiApp;

use App\DBs\WayDB;
use App\DBs\WayUserDB;
use App\Utilitys\FFbase;
use App\Utilitys\FFmpeg;
use App\Utilitys\Logs;
use Illuminate\Http\Request;

class WayUserController extends BaseController
{
    //作品

    protected $db;
    protected $way;
    protected $ffbase;
    protected $ff;
    protected $log;

    public function __construct()
    {
        parent::__construct();
        $this->db = new WayUserDB();
        $this->way = new WayDB();
        $this->ffbase = new FFbase();
        $this->ff = new FFmpeg();
        $this->log = new Logs();
    }

    /**
     * 设置需求
     */
    public function setStuff(Request $request)
    {
        $stamp = $this->getUserStamp();
        if (!$stamp) { return $this->toAppJson(-4); }
        $way = $request->post('way',0);
        $id = $request->post('id',0);
        $type = $request->post('type',0);
        $cover = $request->post('cover','');
        $link = $request->post('link','');
        if (!$way || !$id || !$type || !$cover || !$link) {
            return $this->toAppJson(-2);
        }
        $resOne = $this->db->getAppOneNoRender($stamp,$way);
        if ($resOne['code']!=0) {
            $resWay = $this->way->getOne($way);
            if ($resWay['code']!=0) {
                return $this->toAppJson(-3);
            }
            $files = $resWay['data']['files'];
            foreach ($files as $k => $file) {
                if ($file['id']==$id) {
                    $files[$k]['cover'] = $cover;
                    $files[$k]['link'] = $link;
                }
            }
            $resDb = $this->db->setAppFileAdd($stamp,$way,$files);
            if ($resDb['code']!=0) {
                return $this->toAppJson(-501);
            }
        } else {
            $files = $resOne['files'];
            foreach ($files as $k => $file) {
                if ($file['id']==$id) {
                    $files[$k]['cover'] = $cover;
                    $files[$k]['link'] = $link;
                }
                if (isset($file['dn'])) {
                    unset($files[$k]['dn']);
                }
            }
            $resDb = $this->db->setAppFileUpdate($way,$files);
            if ($resDb['code']!=0) {
                return $this->toAppJson(-501);
            }
        }
        return $this->toAppJson(0);
    }

    /**
     * 申请合成
     */
    public function setApply(Request $request)
    {
        $stamp = $this->getUserStamp();
        if (!$stamp) { return $this->toAppJson(-4); }
        $id = $request->post('id',0);
        $bgmusic = $request->post('bgmusic',''); //背景音地址
        if (!$id) {
            return $this->toAppJson(-2);
        }
        $resOne = $this->db->getOne($id);
        if ($resOne['code']!=0) {
            return $this->toAppJson(-3);
        }
        $one = $resOne['data'];
        if (!$one['files']) {
            return array('code'=>'-500','msg'=>'素材没有');
        }
        $files = json_decode($one['files'], true);
        foreach ($files as $file) {
            if (!file_exists($file['cover']) || !file_exists($file['link'])) {
                return array('code'=>'-500','msg'=>'素材没有2');
            }
        }
        $resDb = $this->db->setAppApply($id,$bgmusic);
        if ($resDb['code']!=0) {
            return $this->toAppJson(-500);
        }
        return $this->toAppJson(0);
    }

    /**
     * 作品列表
     */
    public function getIndex(Request $request)
    {
        $stamp = $this->getUserStamp();
        if (!$stamp) { return $this->toAppJson(-4); }
        $page = $request->post('page',0);
        $size = $request->post('size',10);
        $pageStart = $page * $size;
        $resDb = $this->db->getAppIndex($pageStart,$size,$stamp);
        if ($resDb['code']!=0) {
            return $this->toAppJson(-3);
        }
        $items = $resDb['data']; $total = $resDb['total'];
        return $this->toAppJson(0,$items,$total);
    }

    /**
     * 作品单个
     */
    public function getOne(Request $request)
    {
        $stamp = $this->getUserStamp();
        if (!$stamp) { return $this->toAppJson(-4); }
        $id = $request->post('id',0);
        $resDb = $this->db->getOne($id);
        if ($resDb['code']!=0) {
            return $this->toAppJson(-3);
        }
        $items = [
            'id'=>$resDb['data']['id'],
            'dn'=>env('DOMAIN').'/',
            'cover'=>$resDb['data']['cover'],
            'link'=>$resDb['data']['link'],
        ];
        return $this->toAppJson(0,$items);
    }

    /**
     * 执行合成
     */
    public function setCompose(Request $request)
    {
        ini_set("max_execution_time",0); //不限制执行的时间
        $stamp = $this->getUserStamp();
        if (!$stamp) { return $this->toAppJson(-4); }
        $this->log->setComppose('合成开始：----------');
        $this->log->setComppose('数据获取');
        $resOne = $this->db->getAppLastOneNoRender();
        $this->log->setComppose($resOne);
        if ($resOne['code']!=0) {
            return $this->toAppJson(-3);
        }
        $queryLog = 'logQuerys/composeSwitch.log';
//        return file_put_contents($queryLog,0); //状态复位
        if (!file_exists($queryLog)) {
            file_put_contents($queryLog,0);
        }
        $resFile = file_get_contents($queryLog);
        $this->log->setComppose('状态验证');
        //0空闲1排队中2合成中3已完成
        if ($resFile==1) {
            return array('code'=>'-5','msg'=>'排队中');
        }
        if ($resFile==2) {
            return array('code'=>'-5','msg'=>'合成中');
        }
        if ($resFile==3) {
            return array('code'=>'-5','msg'=>'已是作品');
        }
        //开始合成
        $this->log->setComppose('合成。。。');
        $id = $resOne['data']['id'];
        $files = $resOne['files'];
        $bgmusic = $resOne['data']['bgmusic'];
        file_put_contents($queryLog,2);
        $this->db->setAppFinish($id,3,'','');
        if ($id==1) {
            $resFF = $this->setComIdTo1($files,$bgmusic);
            $this->log->setComppose($resFF);
            if ($resFF['code']!=0) {
                file_put_contents($queryLog,0);
                $this->db->setAppFinish($id,2,'','');
                return array('code'=>'-500','msg'=>'合成失败');
            }
            $resPath = $resFF['data'];
        } else {
            $this->log->setComppose('没有特效');
            file_put_contents($queryLog,0);
            $this->db->setAppFinish($id,2,'','');
            return array('code'=>'-500','msg'=>'没有特效');
        }
        file_put_contents($queryLog,0);
        //获取封面
        $w = 720; $h = 1280;
        $this->log->setComppose('封面。。');
        $resFF2 = $this->ffbase->setMp4ToGif($resPath,$w,$h);
        $this->log->setComppose($resFF2);
        if ($resFF2['code']!=0) {
            $this->db->setAppFinish($id,2,'','');
            return array('code'=>'-500','msg'=>'封面失败');
        }
        $resCover = $resFF2['data'];
        //更新数据
        $this->log->setComppose('更新数据');
        $resDb2 = $this->db->setAppFinish($id,4,$resCover,$resPath);
        $this->log->setComppose($resDb2);
        if ($resDb2['code']!=0) {
            $this->db->setAppFinish($id,2,'','');
            return array('code'=>'-500','msg'=>'状态失败2');
        }
        $this->log->setComppose('合成结束：----------');
        return $this->toAppJson(0);
    }

    /**
     * 合成ID==1
     */
    public function setComIdTo1($files,$bgmusic)
    {
        $w = 720; $h = 1280/3;
        //获取背景音时长
        $resFF4 = $this->ffbase->getVideoDelay($bgmusic);
        if ($resFF4['code']!=0) {
            return array('code'=>'-5','msg'=>'获取时长失败');
        }
        $delay = $resFF4['data'];
        //裁剪素材
        //ffmpeg -i /www/liujiu/quanzi/public/uploads/001.mp4 -vf crop=720:426.666:0 -y /www/liujiu/quanzi/public/uploads/out001.mp4
        $links = array();
        foreach ($files as $file) {
            $resFF = $this->ffbase->setMp4ToCrop($file['link'],$w,$h);
            if ($resFF['code']!=0) {
                $this->setUnlink($links);
                return array('code'=>'-1','msg'=>'素材错误');
            }
            $links[] = $resFF['data'];
        }
        if (count($links)<3) {
            return array('code'=>'-2','msg'=>'素材不足');
        }
        //合成画面
        //ffmpeg \
        //-i /www/liujiu/quanzi/public/uploads/20201125/1606285925739.mp4 \
        //-i /www/liujiu/quanzi/public/uploads/20201125/1606285954228.mp4 \
        //-i /www/liujiu/quanzi/public/uploads/20201125/1606285984231.mp4 \
        //-filter_complex "[0:v]pad=iw:ih*3[a];[a][1:v]overlay=0:h[b];[b][2:v]overlay=0:h*2" \
        //-y /www/liujiu/quanzi/public/uploads/20201125/out002.mp4
        $resFF2 = $this->ff->setCompTo1($links[0],$links[1],$links[2]);
        $this->setUnlink($links);
        if ($resFF2['code']!=0) {
            return array('code'=>'-3','msg'=>'合成画面错误');
        }
        $resMp4 = $resFF2['data'];
        //合成背景音
        //ffmpeg -i /www/liujiu/quanzi/public/input.mp3 -i /www/liujiu/quanzi/public/input.mp4 -t 3 -y /www/liujiu/quanzi/public/out.mp4
        if ($bgmusic) {
            $resFF3 = $this->ffbase->setMp4Mp3ToMp4($resMp4,$bgmusic,$delay);
            $this->setUnlink([$resMp4]);
            if ($resFF3['code']!=0) {
                return array('code'=>'-4','msg'=>'合成背景音错误');
            }
            $resMp4 = $resFF3['data'];
        }
        return array('code'=>'0','msg'=>'success','data'=>$resMp4);
    }

    /**
     * 去除素材
     */
    public function setUnlink($links)
    {
        if (!$links) {
            return array('code'=>'-1','msg'=>'没有link');
        }
        foreach ($links as $link) {
            if (file_exists($link)) { unlink($link); }
        }
        return array('code'=>'0','msg'=>'success');
    }
}